﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using EzDesk.EzAppApi.Utility;

namespace EzDesk.Utility.Web.Controllers
{
    public class EzDeskAppController : EzDeskController
    {

        public class PermissionRequireAttribute : ActionFilterAttribute
        {
            private string _permissionStr;

            public PermissionRequireAttribute(string permissionStr)
            {
                _permissionStr = permissionStr;
            }

            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                base.OnActionExecuting(filterContext);
                
                var userId = ((EzDeskAppController)filterContext.Controller).CurrentUserId;
                var permissionStr = _permissionStr;
                var controller = ((EzDeskAppController)filterContext.Controller);

                var isHasPermisson = controller.EzApiClient.UserHasPermission(permissionStr, userId);

                if (!isHasPermisson)
                {
                    filterContext.Result = new ContentResult() { Content = "您无权访问该页面！" };
                }

            }

        }
        
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var status = filterContext.HttpContext.Request["status"];
            var info = filterContext.HttpContext.Request["info"];
            // 如果发现POST过来了status和info的参数，则让页面自动执行displayInfo脚本
            if (!string.IsNullOrEmpty(status) && !string.IsNullOrEmpty(info))
            {
                var sb = new StringBuilder()
                    .Append(@"<script type=""text/javascript"">")
                    .Append("$(function () {")
                    .Append("$.displayStatusInfo({ Status: '" + status + "', Info: '" + info + "'  });")
                    .Append("});")
                    .Append("</script>");

                ViewData["__PageScripts"] = sb.ToString();
            }

            base.OnActionExecuting(filterContext);
        }

        public IEzApiClient EzApiClient
        {
            get { return EzAppApi.Utility.CacheableEzApiClient.Instance; }
        }
    }
}
